package c2.group.business.tb.rival;

import c2.group.business.tb.TBGroupModule;
import cate.common.table.activity.throne.TBLevelGroupRow;
import cate.common.table.d.GDThrone;
import cate.game.play.part.PlaySide;
import cate.game.pvp.throne.data.rival.TBRivalData;
import cate.game.pvp.throne.data.rival.TBRivalPs;
import cate.game.role.pvp.gradepvp.GradePvpPlayer;
import easy.java.dev.note.NoteClass;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@NoteClass("王座争霸-对手库")
@Slf4j
public class TBRivalModule extends TBGroupModule<TBRivalData> {

	@Override
	protected TBRivalData buildData() {
		return new TBRivalData();
	}

	@Override
	public void readFromBD() {
		for (TBRivalPs rival : useDb().tb.getRivals()) {
			getGroup(rival.group).list.add(rival);
		}
		forGroups(TBRivalData::sort);
	}

	@Override
	public void save() {
		List<TBRivalPs> list = new ArrayList<>();
		for (TBRivalData value : groupMap.values()) {
			list.addAll(value.list);
		}
		useDb().tb.saveRivals(list);
	}

	@Override
	public void clear(){
		forGroups(TBRivalData::clear);
	}

	@Override
	public void onEnterNewSeason() {
	}


	@Override
	public void onPeriodChange(byte period) {
		switch (period) {
			case GDThrone.Period.TRIAL:
				loadPlayers();
				break;
			case GDThrone.Period.KO:
				clear();
				break;
			default:
				break;
		}
	}

	private void loadPlayers(){
		Map<Integer, List<PlaySide>> psMap = new HashMap<>();
		for (GradePvpPlayer player : context.gradePvp.pool.players.values()) {
			TBLevelGroupRow groupRow = useTable().throne.group.getRowByLevel(player.ps.snapshot.base.level);
			if (groupRow == null) {
				continue;
			}
			List<PlaySide> playSides = psMap.computeIfAbsent(groupRow.group, k -> new ArrayList<>());
			playSides.add(player.ps);
		}
		for (Integer group : GDThrone.LevelGroup.ALL) {
			List<PlaySide> playSides = psMap.get(group);
			getGroup(group).setRivals(playSides);
		}
	}

	public void gmAddRivals(int group, List<PlaySide> playSides) {
		TBRivalData rivalData = getGroup(group);
		List<PlaySide> pickList = rivalData.list.stream().map(r -> r.playSide).collect(Collectors.toList());
		pickList.addAll(playSides);
		rivalData.setRivals(pickList);
	}
}
